// pages/userCenter/nearby/nearby.js
const request = require('../../../utils/request')
const utils = require('../../../utils/util')

Page({
  data: {
    page:1,
    shopList:[],
    location: {
      longitude: '',
      latitude: ''
    }
  },

  onLoad() {
    this.getLocation()
  },

  getShopList(longitude, latitude) {
    wx.showLoading()
    // const data = {
    //   x: 38.91379663079788,
    //   y: 121.59637971024094
    // }

    const data = {
      x: latitude,
      y: longitude
    }

    request.get('fujin_repair', data)
      .then(res => {
        wx.hideLoading()
        if (res.data && res.data.length) {
          this.setData({
            shopList: res.data
          })
        }
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        
      })
  },

  getLocation() {
    wx.getLocation({
      type: 'gcj02',
      success: res => {
        this.getShopList(res.longitude, res.latitude)
        this.setData({
          location: {
            longitude: res.longitude,
            latitude: res.latitude
          }
        })
      },
      fail: error => {
        wx.showModal({
          title: '温馨提示',
          content: '您拒绝了获取位置授权，此操作将影响您注册修理厂，若想正常使用此功能，请返回授权',
          showCancel: false,
          confirmText: '返回授权',
          success: res => {
            if (res.confirm) {
              wx.openSetting({
                success: res => {
                  if (res.authSetting['scope.userLocation']) {
                    this.getLocation()
                  }
                }
              })
            }
          }
        })
      }
    })
  },

  toDetail(e) {
    const value = e.currentTarget.dataset
    wx.navigateTo({
      url: `/pages/index/clearCar/clearCar?repairId=${value.id}`
    })
  },

  onPullDownRefresh: utils.throttle(function () {
    this.setData({
      page: 1
    })
    this.getShopList()
  }, 1000),

  onReachBottom: function () {

  },

  toCircuitMap(e) {
    const id = e.currentTarget.dataset.id
    const currentShop = this.data.shopList.find(v => v.id === id)
    const start = JSON.stringify(this.data.location)
    const end = JSON.stringify({
      latitude: currentShop.x,
      longitude: currentShop.y
    })

    wx.navigateTo({
      url: `/pages/userCenter/nearby/circuitMap/circuitMap?start=${start}&end=${end}`
    })
  },
})
